package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user2")
public class UserController2 {

    @Autowired
    private UserService userService;

    @RequestMapping("/del")
    // 在方法开始之前开启事务，方法正常执行执行结束之后提交事务，如果执行途中发生异常，则回滚事务
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public int del(Integer id) {
        if(id == null || id <= 0) return 0;
        int result = userService.del(id);
        System.out.println("删除：" + result);
        try{
            int num = 10/0;
        } catch (Exception e) {
//            throw e;
            // 异常处理，ex 记录错误、提示报警信息。。。
            // 手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }
}
